package com.glory.eapequipmentmonitor.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.eapequipmentmonitor.R;
import com.glory.eapequipmentmonitor.adapter.LotListAdapter;
import com.glory.eapequipmentmonitor.adapter.ScrapListAdapter;
import com.glory.eapequipmentmonitor.adapter.ThingListAdapter;
import com.glory.eapequipmentmonitor.base.Constant;
import com.glory.eapequipmentmonitor.bean.LotBean;
import com.glory.eapequipmentmonitor.bean.ScrapBean;
import com.glory.eapequipmentmonitor.bean.ThingBean;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EndWorkActivity extends FreeUI_BaseActivity {


    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.etNum)
    FreeUI_ClearEditText etNum;
    @BindView(R.id.ivDownArrow)
    ImageView ivDownArrow;
    @BindView(R.id.rlInfo)
    RelativeLayout rlInfo;
    @BindView(R.id.rvInfoList)
    RecyclerView rvInfoList;
    @BindView(R.id.rvThingList)
    RecyclerView rvThingList;
    @BindView(R.id.tvCarryId)
    TextView tvCarryId;
    @BindView(R.id.tvLotTitle)
    TextView tvLotTitle;
    @BindView(R.id.llScrap)
    LinearLayout llScrap;
    @BindView(R.id.tvScrap)
    TextView tvScrap;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.llEnd)
    LinearLayout llEnd;
    @BindView(R.id.etEndNum)
    FreeUI_ClearEditText etEndNum;
    @BindView(R.id.tvLotNum)
    TextView tvLotNum;
    @BindView(R.id.llLotNum)
    LinearLayout llLotNum;

    private boolean isLot = true;
    private Animation animation, animationDismiss;
    private ScrapListAdapter scrapListAdapter;
    private LotListAdapter lotListAdapter;
    private List<ThingBean> mLots = new ArrayList<>();
    private ThingListAdapter thingListAdapter;
    private FreeUI_GeneralFragmentDialog addCarryIdDialog;
    private List<LotBean> scrapList = new ArrayList<>();
    private boolean isEnd = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1101 && data != null) {
            LotBean resultLotBean = (LotBean) data.getSerializableExtra("resultLotBean");
            if (resultCode == 2101) {
                for (LotBean lotBean : lotListAdapter.getData()) {
                    if (lotBean.getLOTID().equals(resultLotBean.getLOTID())) {
                        lotBean.setWrite(true);
                    }
                }
                Iterator<LotBean> iterator = scrapList.iterator();
                while (iterator.hasNext()) {
                    LotBean lotBean = iterator.next();
                    if (lotBean.getLOTID().equals(resultLotBean.getLOTID())) {
                        iterator.remove();
                    }
                }
                scrapList.add(resultLotBean);
            } else if (resultCode == 2102) {
                for (LotBean lotBean : lotListAdapter.getData()) {
                    if (lotBean.getLOTID().equals(resultLotBean.getLOTID())) {
                        lotBean.setWrite(false);
                    }
                }
                Iterator<LotBean> iterator = scrapList.iterator();
                while (iterator.hasNext()) {
                    LotBean lotBean = iterator.next();
                    if (lotBean.getLOTID().equals(resultLotBean.getLOTID())) {
                        iterator.remove();
                    }
                }
            }
            lotListAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.ivAdd, R.id.rlInfo, R.id.rlCarryId, R.id.rbLot, R.id.rbWork, R.id.rbYes, R.id.rbNo})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rbYes:
                isEnd = true;
                break;
            case R.id.rbNo:
                isEnd = false;
                break;
            case R.id.rbLot:
                isLot = true;
                tvLotTitle.setText("生产批号：");
                etLotId.setHint("请扫描生产批号");
                etLotId.setText("");
                tvStep.setText("");
                llEnd.setVisibility(View.GONE);
                etEndNum.setText("");
                llLotNum.setVisibility(View.VISIBLE);
                tvLotNum.setText("");
                llScrap.setVisibility(View.VISIBLE);
                tvScrap.setText("报废信息列表");
                if (rvInfoList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow.startAnimation(animationDismiss);
                    rvInfoList.setVisibility(View.GONE);
                }
                scrapListAdapter.setNewData(null);
                rvInfoList.setAdapter(scrapListAdapter);
                break;
            case R.id.rbWork:
                isLot = false;
                tvLotTitle.setText("工单号　：");
                etLotId.setHint("请扫描工单号");
                etLotId.setText("");
                tvStep.setText("");
                llScrap.setVisibility(View.GONE);
                llEnd.setVisibility(View.GONE);
                etEndNum.setText("");
                llLotNum.setVisibility(View.GONE);
                tvLotNum.setText("");
                tvScrap.setText("批次信息列表");
                if (rvInfoList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow.startAnimation(animationDismiss);
                    rvInfoList.setVisibility(View.GONE);
                }
                lotListAdapter.setNewData(null);
                rvInfoList.setAdapter(lotListAdapter);
                break;
            case R.id.ivAdd:
                final FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog = new FreeUI_GeneralFragmentDialog();
                View view = LayoutInflater.from(EndWorkActivity.this).inflate(R.layout.dialog_scan_thing, null);
                TextView tvCancel = view.findViewById(R.id.tvCancel);
                final FreeUI_ClearEditText etThingCode = view.findViewById(R.id.etThingCode);
                final FreeUI_ClearEditText etThingId = view.findViewById(R.id.etThingId);
                etThingCode.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (start == 0 && before == 0 && count > 1) {
                            if (etThingId.getText().toString().trim().length() > 0) {
                                setList(etThingCode.getText().toString().trim(), etThingId.getText().toString().trim());
                                freeUI_generalFragmentDialog.dismiss();
                            } else {
                                etThingId.requestFocus();
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                etThingId.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (start == 0 && before == 0 && count > 1) {
                            if (etThingCode.getText().toString().trim().length() > 0) {
                                setList(etThingCode.getText().toString().trim(), etThingId.getText().toString().trim());
                                freeUI_generalFragmentDialog.dismiss();
                            } else {
                                etThingCode.requestFocus();
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        freeUI_generalFragmentDialog.dismiss();
                    }
                });
                freeUI_generalFragmentDialog.setLayout(view);
                freeUI_generalFragmentDialog.show(getSupportFragmentManager(), "11");
                break;
            case R.id.rlInfo:
                arrowAnimation();
                break;
            case R.id.rlCarryId:
                addCarryIdDialog = FreeApi_DialogUtils.getScanDialog(this, "请扫描载具编号", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        String carryIds = tvCarryId.getText().toString().trim();
                        boolean isSame = false;
                        if (carryIds.length() == 0) {
                            tvCarryId.setText(s);
                        } else {
                            if (carryIds.contains(";")) {
                                String[] array = carryIds.split(";");
                                for (String str : array) {
                                    if (str.equals(s)) {
                                        isSame = true;
                                    }
                                }
                            } else {
                                if (carryIds.equals(s)) {
                                    isSame = true;
                                }
                            }
                            if (isSame) {
                                showToast("载具编号不能重复", false);
                            } else {
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append(carryIds);
                                stringBuffer.append(";");
                                stringBuffer.append(s);
                                tvCarryId.setText(stringBuffer.toString());
                            }
                        }
                        addCarryIdDialog.dismiss();
                    }
                });
                addCarryIdDialog.show(getSupportFragmentManager(), "addCarryIdDialog");
                break;
        }
    }

    private void setList(String matCode, String matLotId) {
        String seq = String.valueOf(mLots.size() + 1);
        mLots.add(new ThingBean(seq, matCode, matLotId));
        thingListAdapter.notifyDataSetChanged();
    }

    private void arrowAnimation() {
        if (rvInfoList.getVisibility() == View.VISIBLE) {
            if (animationDismiss == null) {
                animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animationDismiss.setDuration(500);
                animationDismiss.setFillAfter(true);
            }
            ivDownArrow.startAnimation(animationDismiss);
            rvInfoList.setVisibility(View.GONE);
        } else {
            if (animation == null) {
                animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(500);
                animation.setFillAfter(true);
            }
            ivDownArrow.startAnimation(animation);
            rvInfoList.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_end_work;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        freeUI_titleView.setTitle("结束作业");
        freeUI_titleView.setRightListener("提交", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String lotId = etLotId.getText().toString().trim();
                if (lotId.length() == 0) {
                    showToast("请扫描生产批号", false);
                    return;
                }
                String carryId = tvCarryId.getText().toString().trim();
                if (carryId.length() == 0 && Constant.IS_CARRIER.equalsIgnoreCase("Y")) {
                    showToast("请扫描载具编号", false);
                    return;
                }
                String scrapNum = etNum.getText().toString().trim();
                if (isLot && scrapNum.length() > 0) {
                    scrapList = new ArrayList<>();
                    int listNum = 0;
                    List<ScrapBean> qtyList = new ArrayList<>();
                    for (ScrapBean scrapBean : scrapListAdapter.getData()) {
                        if (scrapBean.getQTY().length() > 0) {
                            qtyList.add(scrapBean);
                            listNum += Integer.parseInt(scrapBean.getQTY());
                        }
                    }
                    if (Integer.parseInt(scrapNum) != listNum) {
                        showToast("报废数量必须等于报废列表总和", false);
                        return;
                    }
                    scrapList.add(new LotBean(lotId, scrapNum, qtyList));
                }
                if (mLots.size() == 0 && Constant.IS_MATERIAL.equalsIgnoreCase("Y")) {
                    showToast("请添加物料", false);
                    return;
                }
                String endNum = etEndNum.getText().toString().trim();
                if (endNum.length() == 0 && llEnd.getVisibility() == View.VISIBLE) {
                    showToast("请输入剩余芯片数量", false);
                    return;
                }
                showToast("结束作业成功", true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EndWorkActivity.this.finish();
                    }
                }, 2000);

            }
        });

        rvInfoList.setLayoutManager(new LinearLayoutManager(EndWorkActivity.this));
        rvInfoList.setItemAnimator(new DefaultItemAnimator());
        rvInfoList.addItemDecoration(new DividerItemDecoration(EndWorkActivity.this, 1));
        scrapListAdapter = new ScrapListAdapter(null);
        scrapListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        scrapListAdapter.isFirstOnly(true);

        lotListAdapter = new LotListAdapter(null);
        lotListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lotListAdapter.isFirstOnly(true);
        lotListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LotBean lotBean = (LotBean) adapter.getItem(position);
                Intent intent = new Intent(EndWorkActivity.this, ScrapListActivity.class);
                intent.putExtra("lotBean", lotBean);
                intent.putExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY, "header");
                startActivityForResult(intent, 1101);
            }
        });
        if (isLot) {
            rvInfoList.setAdapter(scrapListAdapter);
        } else {
            rvInfoList.setAdapter(lotListAdapter);
        }

        rvThingList.setLayoutManager(new LinearLayoutManager(EndWorkActivity.this));
        rvThingList.setItemAnimator(new DefaultItemAnimator());
        rvThingList.addItemDecoration(new DividerItemDecoration(EndWorkActivity.this, 1));
        thingListAdapter = new ThingListAdapter(mLots);
        thingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        thingListAdapter.isFirstOnly(true);
        rvThingList.setAdapter(thingListAdapter);
    }

    @Override
    protected void initData() {
        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (isLot) {
                        requestScrap(s.toString());
                    } else {
                        requestLots(s.toString());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void requestScrap(String lotId) {
        List<ScrapBean> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            ScrapBean scrapBean = new ScrapBean();
            scrapBean.setDESCRIPTION("报废信息" + i);
            list.add(scrapBean);
        }
        scrapListAdapter.setNewData(list);
        tvStep.setText("T-STEP_101");
        tvLotNum.setText("33");
        etRemark.requestFocus();
    }

    private void requestLots(String woId) {
        List<LotBean> list = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            LotBean lotBean = new LotBean();
            lotBean.setLOTID("T-LOT10872" + i);
            list.add(lotBean);
        }
        lotListAdapter.setNewData(list);
        tvStep.setText("T-STEP_101");
        tvLotNum.setText("12");
        etRemark.requestFocus();
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity("header", llMain);
    }
}
